package org.calzz.rpc.get;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.calzz.rpc.envelope.JsonRequest;

/**
 * Default implementation of the <code>IUrlMappingStrategy</code>. Accepts
 * only classic URL format.
 * 
 * @author Marek Brodziak <marek.brodziak@gmail.com>
 * @author Piotr Pejas <piotr.pejas@gmail.com>
 * @since Mar 8, 2008
 */
public class DefaultUrlMappingStrategy implements IUrlMappingStrategy {

	/*
	 * (non-Javadoc)
	 * @see org.calzz.rpc.get.IUrlMappingStrategy#doMapping(javax.servlet.http.HttpServletRequest,
	 *      org.calzz.rpc.envelope.JsonRequest)
	 */
	@Override
	public JsonRequest doMapping(HttpServletRequest httpRequest) {
		JsonRequest jsonRequest = new JsonRequest();

		String requestPath = httpRequest.getPathInfo();
		jsonRequest.setMethod(requestPath.substring(requestPath.lastIndexOf('/') + 1));

		Map<String, Object> params = new HashMap<String, Object>();
		@SuppressWarnings("unchecked")
		Map<String, Object> paramMap = httpRequest.getParameterMap();
		for (String key : paramMap.keySet()) {
			Object value = paramMap.get(key);
			if (value.getClass().isArray()) {
				params.put(key, Arrays.asList((Object[]) value));
			} else {
				params.put(key, value);
			}
		}
		jsonRequest.setParams(params);

		return jsonRequest;
	}

}
